<template>
  <div>
    <el-dialog
      title="提示"
      :visible="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <!-- 内容表单 -->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="ruleForm.phone" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="ruleForm.address" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="ruleForm.desc" />
        </el-form-item>
        <el-form-item label="封面" prop="image">
          <ImgUpload ref="ImgUpload" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addAgents, uploadAgent } from '@/api/agents'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      ruleForm: {
        name: '',
        email: '',
        phone: '',
        address: '',
        desc: '',
        image: ''

      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    // 清空表单并关闭
    handleClose() {
      this.ruleForm = {
        name: '',
        email: '',
        phone: '',
        address: '',
        desc: '',
        image: ''
      }
      this.$refs.ruleForm.resetFields()
      this.$refs.ImgUpload.fileList = []
      this.$emit('update:dialogVisible', false)
    },
    // 确认发起请求
    async confirm() {
      await this.$refs.ruleForm.validate()
      // 发起请求前，先确定图片已经上传完毕
      if (this.$refs.ImgUpload.percentage !== 100) {
        return this.$message({
          type: 'warning',
          message: '图片上传中，请稍等'
        })
      }
      // 把插件里的图片拿过来
      this.ruleForm.image = this.$refs.ImgUpload.fileList[0].url
      //  判断是编辑还是新增
      if (this.ruleForm.id) {
        await uploadAgent(this.ruleForm)
      } else {
        await addAgents(this.ruleForm)
      }
      this.handleClose()
      // 重新渲染
      this.$emit('uploadWeb')
    }
  }
}
</script>

<style>

</style>
